#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define N 128

int main(int argc,char const *argv[])
{
    //终端传参数是否符合要求
    if(argc < 3)
    {
        //参数个数不符合，输出错误
        fprintf(stderr,"Uasge:%s ip port\n",argv[0]);
        exit(-1);
    }

    //第一步：创建套接字
    int my_sock;
    if((my_sock = socket(AF_INET,SOCK_DGRAM,0)) == -1)
    {
        perror("fail to socket");
        exit(-1);
    }

    //第二步：初始化ip地址结构体
    struct sockaddr_in server_addr;
    socklen_t addrlen = sizeof(server_addr);
    server_addr.sin_family = AF_INET;
    //终端传入本地服务器ip地址、端口号
    server_addr.sin_addr.s_addr = inet_addr(argv[1]);
    server_addr.sin_port = htons(atoi(argv[2]));

    //第三步：发送数据，接收服务端处理数据
    char buf_send[N] = "";
    char buf_recv[N] = "";
    while(1)
    {
        //发送数据
        memset(buf_send,0,N);
        fgets(buf_send,N,stdin);
        buf_send[strlen(buf_send)-1] = '\0';
        if(sendto(my_sock,buf_send,N,0,(struct sockaddr *)&server_addr,addrlen) == -1)
        {
            perror("fail to sendto");
            exit(-1);
        }
        //接收服务端处理数据
        memset(buf_recv,0,N);
        if(recvfrom(my_sock,buf_recv,N,0,(struct sockaddr*)&server_addr,&addrlen) == -1)
        {
            perror("fail to recvfrom");
            exit(-1);
        }
        printf("from server[%s\t%d]:%s\n",inet_ntoa(server_addr.sin_addr),ntohs(server_addr.sin_port),buf_recv);
    }

    //第四步：关闭套接字
    close(my_sock);
    return 0;
}